var _account_service = require('service/account-service.js');
var _catalog_service=require('service/catalog-service.js')
require('./header.css')
require('../../common/mypetstore.css')

var header = {
    init : function(){
        this.loadAccountInfo();
        this.bindEvents();
        return this;
    },

    //向服务器获取已登录账号
    loadAccountInfo : function(){
        _account_service.checkLogin(
            //收到服务器的响应
            function(res){
                // 已经登录
                if(res.status === 0){
                    $('#MenuContent').html(`<a href="../cart/cart.html"><img align="middle" name="img_cart" src="../../images/cart.gif" /></a>
                                            <img class="myAccount" align="middle" src="../../images/separator.gif" />
                                            <a class="myAccount" href="../../view/account/myAccount.html">My Account</a>
                                            <img class="myOrders" align="middle" src="../../images/separator.gif" />
                                            <a class="myOrders" href="../../view/order/my-orders.html">My Orders</a>
                                            <img class="signOut" align="middle" src="../../images/separator.gif" />
                                            <a class="signOut">Sign Out</a>
                                            <img align="middle" src="../../images/separator.gif" />
                                            <a href="/catalog/help">?</a>`);
                    //为Sign Out绑定单击事件
                    $('.signOut').on('click',function (param) {
                        _account_service.signOut(
                            function(res){
                                if(res.status===0)
                                    window.location.href='../../../view/catalog/catalog-main.html'
                                else if(res.status===1){
                                    alert(res.msg);
                                    window.location.href='../../../view/account/login.html'
                                }
                            },
                            function(errMsg){
                                alert('服务器异常')
                            }
                        )
                    });
                    
                    //显示底部的banner
                    if(res.data.bannerOption){
                        $('#Banner').html(`<label>${res.data.bannerName}</label>`)
                    }
                }
                //没有登录
                else if(res.status === 11){
                    $('#MenuContent').html(`<a href="../cart/cart.html"><img align="middle" name="img_cart" src="../../images/cart.gif"/></a>
                                            <img class="signIn" align="middle" src="../../images/separator.gif" />
                                            <a class="signIn" href="../account/login.html?redirect=/view/catalog/catalog-main.html">Sign In</a>
                                            <img align="middle" src="../../images/separator.gif" />
                                            <a href="/catalog/help">?</a>`);
                    //为Sign In按钮绑定单击事件
                    //点击登录按钮：
                    $('.signIn').on('click',function (param) {
                        window.location.href='../../../view/account/login.html?redirect='+encodeURIComponent(window.location.href);
                    })                                
                };   
            },
            //没有收到服务器的响应
            function(errMsg){
            }
        );
    },

    //绑定事件
    bindEvents: function(){
          //点击搜索按钮
          $('#searchBtn').on('click',function(){
            let data={
                keywords:$('#key').val()
            };
              if(!data.keywords) return         //搜索框为空时则不进行搜索
              _catalog_service.getProductByKey(
                  data,
                  function ({data:res}) { 
                    //   注意：session传值时只能传字符串
                    sessionStorage.setItem('searchProductList',JSON.stringify(res))
                    window.location.href='../../../view/catalog/search-products.html'
                   },
                  function (errMsg) { 
                      alert(errMsg.msg)
                   })

          }),

          //自动补全事件：
          $('#key').on('keyup',function(){
            // $('#container').html('<div>'+'aaaaaa'+'</div>')
            // console.log('已经设置了值')
            let category=[
            {id:'BIRDS',name:[]},
            {id:'FISH',name:[]},
            {id:'DOGS',name:[]},
            {id:'REPTILES',name:[]},
            {id:'CATS',name:[]}
        ];
            
            let data={
                keywords:$('#key').val()
            };
            if(!data.keywords) {
                $('#container').hide();
                return};
            $('#container').show();
            _catalog_service.getProductByKey(
                data,
                function(res){
                    if(!res.data){
                        $('#container').hide();
                        return;
                    }
                    $('#container').show();
                    res=res.data;
                    res.forEach(element => {
                        category.forEach(item=>{
                            element.categoryId===item.id&&item.name.push(element.name);
                        })
                    });
                    let add='';
                    category.forEach(element=>{
                        if(element.name.length!==0){
                            add+=`<div class="category">${element.id}</div>`
                            if(element.name.length!==0){
                                element.name.forEach(item=>{
                                    add+=`<div class="item">${item}</div>`
                                })
                            }
                        }
                    })
                     add+='</div>'
                     $('#container').html(add)
                     //绑定点击事件（必须紧跟在数据渲染的部分）
                     $('.item').each(function () {
                        $(this).on('click',function () {
                            let data={
                                keywords:$(this).text()
                            };
                            _catalog_service.getProductByKey(
                                data,
                                function ({data:res}) { 
                                  //   注意：session传值时只能传字符串
                                  sessionStorage.setItem('searchProductList',JSON.stringify(res))
                                  window.location.href='../../../view/catalog/search-products.html'
                                 },
                                function (errMsg) { 
                                    alert(errMsg.msg)
                                 })
                        })
                      })
                     
                },
                function(){}
            )

          });
          



    }
};

module.exports = header.init();